<template>
  <el-dialog :destroy-on-close="true" :lock-scroll="false" :title="form_title" :visible.sync="visible"
             width="750px">
    <!--    form start   -->
    <el-form ref="product_form" :model="product_form" :rules="rules" label-width="82px">
      <el-form-item label="所属客户" prop="customer_name">
        <el-autocomplete v-model="product_form.customer_name" :fetch-suggestions="querySearchCustomer"
                         disabled
                         placeholder="请搜索所属客户"
                         value-key="name" @select="handleSelectCustomer">
          <template v-slot="{ item }">
            <div style="color: #333;"><b>{{ item ? item.name : '' }}</b></div>
            <div class="name" style="margin-top: -4px; display: flex;">
              电话: <span style="margin-right: 14px;">{{ item.user ? item.user.phone : '无' }}</span>
              编号: <span style="margin-right: 14px;">{{ item.customer_number }}</span>
              联系人: <span>{{ item.user ? item.user.name : '无联系人' }}</span>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="出厂编号" prop="name">
        <el-input v-model="product_form.name" placeholder="请输入出厂编号"/>
      </el-form-item>
      <el-form-item label="设备型号" prop="type_name">
        <el-autocomplete v-model="product_form.type_name" :fetch-suggestions="querySearchType"
                         placeholder="请搜索设备型号"
                         value-key="name" @select="selectProductItem"/>
      </el-form-item>
<!--      <el-form-item label="服务网点:" prop="department_id">-->
<!--        <TreeSelect-->
<!--          v-model="product_form.department_id"-->
<!--          :options="deptList"-->
<!--          placeholder="请选择网点"-->
<!--          :defaultExpandLevel="3"-->
<!--          :normalizer="(d)=>{return { id: d.id, label: d.name,children:d.children||undefined }}"/>-->
<!--      </el-form-item>-->

      <el-form-item label="所属区域:" prop="city">
        <div class="area">
          <City @areaChange="areaChange" :ids="cityName" ref="city" disabled/>
        </div>
      </el-form-item>

      <el-form-item label="详细地址" prop="install_address">
        <el-input v-model="product_form.install_address" placeholder="请输入详细地址" disabled/>
      </el-form-item>

      <el-form-item label="购买日期" prop="date_buy">
        <el-date-picker v-model="product_form.date_buy" class="c-picker" placeholder="选择购买日期" type="date"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>
      <el-form-item label="验收日期" >
        <el-date-picker v-model="product_form.date_check" class="c-picker" placeholder="选择验收日期" type="date"
                        value-format="yyyy-MM-dd"/>
      </el-form-item>
      <el-form-item label="出厂报告">
        <template>
          <el-upload
            :file-list="fileList"
            :http-request="upload"
            :limit="1"
            :on-change="uploadHandleChange"
            :show-file-list="false"
            accept=".xls,.xlsx,.docx,application/msword,application/vnd.ms-excel,application/pdf"
            action="#"
            class="upload-demo"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls/xlsx/docx/pdf文件，且不超过10M</div>
          </el-upload>

          <span v-if="product_form.attachment" key="1" style="color: deepskyblue">
            {{ product_form.attachment }}
            <span style="cursor: pointer;color: black" @click="delAttachment">&nbsp;&nbsp;删除</span></span>
        </template>
      </el-form-item>
      <el-form-item label="保质期">
        <template>
          <el-radio-group v-model="radio" @change="selectType">
            <el-radio v-model="product_form.warranty_type" label="at">自动计算</el-radio>
            <el-radio v-model="product_form.warranty_type" label="mt">手动添加</el-radio>
          </el-radio-group>
        </template>
        <template>
          <div v-if="product_form.type_name && product_form.warranty_type === 'at'"
               class="p-3 bg-gray-100 mb-2 leading-normal">
            <div class="mb-1 text-black">计算规则</div>
            <div class="text-xs">
              质保期时长：{{ productType.warranty_cycle_count || '' }}
              {{ productType.warranty_start_unit==='year'?'年':'月' }}
            </div>
          </div>

          <div v-if="product_form.type_name || product_form.warranty_type === 'mt'">
            <el-date-picker v-model="product_form.warranty_start" class="c-picker" placeholder="质保开始日期"
                            size="small"
                            type="date" value-format="yyyy-MM-dd" @change="changeStartTime"/>
            <el-date-picker v-model="product_form.warranty_end" :disabled="product_form.warranty_type === 'at'"
                            :picker-options="product_form.endTimeOptions" placeholder="质保结束日期" size="small"
                            type="date"
                            value-format="yyyy-MM-dd"/>
            <div>质保状态: {{ expirationStatus }}</div>
          </div>
        </template>
        <el-alert v-if="product_form.warranty_type === 'at' && !product_form.type_name" :closable="false"
                  class="h-8 py-0" show-icon
                  title="未选择产品类型，无法进行自动计算。请选择&quot;产品类型&quot;或&quot;手动添加&quot;"
                  type="warning"/>
      </el-form-item>
    </el-form>
    <!--    form end     -->
    <div slot="footer">
      <el-button @click="handleCancel()">取消</el-button>
      <el-button :loading="loading" type="primary" @click="handleSave('product_form')">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Moment from "moment/moment";
import City from '@/components/city'
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: "product-form",
  components: { City},
  data() {
    const validateAreas = (rule, value, callback) => {
      // 判断 country_id province_id city_id county_id 是否为空
      if (!this.city.length) {
        callback(new Error("请选择地区"));
      } else {
        callback();
      }
    };
    const validateInstall_address = (rule, value, callback) => {
      // 判断 country_id province_id city_id county_id 是否为空
      if (!this.product_form.install_address) {
        callback(new Error("请输入详细地址"));
      } else {
        callback();
      }
    };

    return {
      //省市区回显
      cityName: '',
      // 选择的省市区
      city: [],
      deptList: null,
      type: null,
      visible: false,
      rules: {
        city: [
          {required: true, trigger: "change", validator: validateAreas}
        ],
        name: [
          {required: true, message: "请输入产品名称", trigger: "blur"}
        ],
        customer_name: [{required: true, message: "请搜索所属客户", trigger: "change"}],
        type_name: [{required: true, message: "请搜索产品类型", trigger: "change"}],
        department_id: [{required: true, message: "请选择服务网点", trigger: "change"}],
        install_address: [
          {required: true, validator: validateInstall_address, trigger: "blur"}
        ],
        date_buy: [
          {required: true, message: "请选择购买日期", trigger: "blur"}
        ],
        date_check: [
          {required: true, message: "请选择验收日期", trigger: "blur"}
        ],
        address: [
          {required: true, message: "请输入详细地址", trigger: "blur"}
        ],
      },
      product_form: {
        customer: {},
        qrcode: {},
        type: {},
        customer_name:'',
        cityName:'',
        customer_id:''
      },
      form_title: "",
      loading: false,
      deptLists: [],
      fileList: [],
      //选择文件保质期方式
      radio: "at",
      productType: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  mounted() {
    /**获取服务网点*/
  },
  computed: {
    expirationStatus() {
      if (!this.product_form.warranty_start) {
        return '请选择日期';
      }
      if (this.product_form.warranty_end < Moment().format('YYYY-MM-DD')) {
        return '保外';
      } else {
        return '保内';
      }
    }
  },

  methods: {
    areaChange(val) {
      this.city = val
    },
    /**
     * @param type 弹窗类型
     * @param form 表单数据（建议后期优化为从后端获取数据）
     */
    showDialog(type,data) {
      this.visible = true;
      this.type = type;
      this.city = [data.province_id, this.$route.query.city_id, data.county_id]
      this.product_form.customer_id=data.customer_id
      this.product_form.customer_name=data.customer_name
      this.$nextTick(()=>{
        this.$refs.city.addressIds = data.province_name + '/' + data.city_name + '/' + data.county_name
      })
      this.product_form.install_address=data.address
      this.product_form.warranty_type = "at"
      this.form_title = "添加产品"
    },
    /** 保存事件 **/
    handleSave(val) {
      this.$refs[val].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.product_form = Object.assign({}, this.product_form, {
          province_id: this.city[0],
          city_id: this.city[1],
          county_id: this.city[2]
        });
        this.type === "add" ? this.addProduct(this.product_form) : this.editProduct(this.product_form)
      });
    },
    // 新增产品
    addProduct(params) {
      this.$http.post('/products', params).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.handleCancel();
          this.$emit("done",res.data.data)
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    },
    // 编辑产品
    editProduct(params) {
      this.$http.put('products/' + params.id, params).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.handleCancel();
          this.$emit("reload")
        }
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    },
    /** 取消事件 **/
    handleCancel() {
      if (!this.isUpdate) {
        this.form = {}
        this.city = []
      }
      this.visible = false;
      this.$refs['product_form'].resetFields();
    },
    /**--- 逻辑处理 start ---**/
    querySearchCustomer(query, cb) {
      this.$http.get("customers", {
        params: {
          keyword: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    handleSelectCustomer(item) {
      this.product_form.customer_id = item.id;
    },
    querySearchType(query, cb) {
      this.$http.get("product_types", {
        params: {
          name: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    selectProductItem(item) {
      this.productType = item
      this.product_form.type_id = item.id;
    },
    upload(file) {
      const formData = new FormData();
      formData.append("attachment", file.file);
      this.$http.post("files/filesStore", formData).then((res) => {
        this.product_form.attachment = res.data.data.path;
        //聚焦刷新
        this.$forceUpdate()
      });
    },
    uploadHandleChange(file) {
      if (file.status === "error") {
        this.$message.error("上传失败");
      }
    },
    arrayToTree(array, pid) {
      let result = []
      array.forEach(item => {
        if (item.pid === pid) {
          item.children = this.arrayToTree(array, item.id)
          result.push(item)
        }
      })
      return result
    },


    delAttachment() {
      this.fileList = []
      this.product_form.attachment = ''
    },
    selectType(val) {
      this.product_form.warranty_type = val
      this.$forceUpdate()
    },
    changeStartTime() {
      // 当 product_form.warranty_type 为 mt 自动计算时，保质期结束时间自动计算 + 质保期时长
      if (this.product_form.warranty_type !== 'mt') {
        this.product_form.warranty_end = Moment(this.product_form.warranty_start).add(this.productType.warranty_cycle_count, this.productType.warranty_start_unit).format('YYYY-MM-DD');
        this.$forceUpdate()
      }
    },
    /**--- 逻辑处理 end ---**/
  }
}
</script>

<style scoped>
.area /deep/ input {
  width: 628px;
}
/deep/ .el-input{
  width: 100%;
}

/deep/ .el-autocomplete{
  width: 100%;
}

</style>
